<template>
	<s-layout title="打包出库">
		<view class="cicon-notice"
		      style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
			<text>操作类型：普通-操作普通包裹；合箱-操作分类箱子</text>
		</view>
		<su-sticky bgColor="#fff">
			<su-tabs
					:list="tabMaps"
					:scrollable="true"
					@change="onTabsChange"
					:current="state.currentTab"
			></su-tabs>
		</su-sticky>
		<uni-forms
				ref="addressFormRef"
				v-model="state.model"
				validateTrigger="bind"
				labelWidth="160"
				labelAlign="left"
				border
				:labelStyle="{ fontWeight: 'bold' }"
		>
			<view class="bg-white form-box ss-p-x-30">

				<uni-forms-item v-if="state.currentTab === 0 || state.currentTab === 1" name="wmsType" label="操作类型" class="form-item">
					<radio-group @change="onRefundChange">
						<label
								class="ss-flex ss-col-center ss-p-y-10"
								v-for="(item, index) in state.model.wareTypeList"
								:key="index"
						>
							<radio
									:checked="state.model.wmsType === item.value"
									color="var(--ui-BG-Main)"
									style="transform: scale(0.8)"
									:value="item.value"
							/>
							<text>{{ item.text }}</text>
						</label>
					</radio-group>
				</uni-forms-item>

				<uni-forms-item name="expressNo" label="包裹编号" class="form-item">
					<uni-easyinput
							v-model="state.model.expressNo"
							placeholder="请填写包裹编号"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							<button style="width: 120rpx; color: #FFFFFF; background: #459cff" class="ss-reset-button ui-Shadow-Main" @tap="onScanPackNumber">扫码</button>
						</template>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item v-if="state.currentTab === 0" name="productId" label="商品ID" class="form-item">
					<uni-easyinput
							v-model="state.model.productId"
							placeholder="商品ID"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item v-if="state.currentTab === 1" name="wareName" label="商品名称" class="form-item">
					<uni-easyinput
							v-model="state.model.wareName"
							placeholder="商品名称"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
					</uni-easyinput>
				</uni-forms-item>

				<!--<uni-forms-item v-if="state.currentTab === 1" name="targetExpressNo" label="合箱编号" class="form-item">
					<uni-easyinput
							v-model="state.model.targetExpressNo"
							placeholder="请填写合箱编号"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							<button style="width: 120rpx; color: #FFFFFF; background: #459cff" class="ss-reset-button ui-Shadow-Main" @tap="onScanBigPackNumber">扫码</button>
						</template>
					</uni-easyinput>
				</uni-forms-item>-->

				<!--<uni-forms-item v-if="state.currentTab === 1" name="expressNo" label="包裹编号" class="form-item">
					<uni-easyinput
							v-model="state.model.expressNo"
							disabled
							placeholder="包裹编号"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
					</uni-easyinput>
				</uni-forms-item>-->

				<uni-forms-item
						v-if="state.currentTab === 0"
						name="packPics"
						label="拍摄图片"
						class="form-item"
				>
					<uni-file-picker
							@delete="e => onDelete(e)"
							ref="uploadStorage"
							v-model="state.model.pickerVal"
							fileMediatype="image"
							limit="10"
							:auto-upload="false"
							@select="e => onSelect(e)"
							>
					</uni-file-picker>
				</uni-forms-item>

				<uni-forms-item
						v-if="state.currentTab === 1"
						name="packPics"
						label="商品图片"
						class="form-item"
				>
					<uni-file-picker
							@delete="e => onDelete(e)"
							ref="uploadStorage"
							v-model="state.model.pickerVal"
							fileMediatype="image"
							limit="1"
							:auto-upload="false"
							@select="e => onSelect(e)"
					>
					</uni-file-picker>
				</uni-forms-item>

				<uni-forms-item v-if="state.currentTab === 0" name="freightHeight" label="包裹重量" class="form-item">
					<uni-easyinput
							v-model="state.model.freightHeight"
							placeholder="请填写包裹重量"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							kg
						</template>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item v-if="state.currentTab === 0" name="size" label="包裹尺寸" class="form-item">
					<uni-easyinput
							v-model="state.model.size"
							placeholder="请填写包裹尺寸"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					/>
				</uni-forms-item>
			</view>
		</uni-forms>
		<view v-if="!sheep.$helper.isRealEmpty(state.expressInfo.detail.id)">
			<view style="font-size: 40rpx; font-weight: bold; text-align: center">包裹编号：{{ state.model.expressNo }}</view>
			<br>
			<view v-for="orderId in state.expressInfo.detail.orderIdList"
			      style="font-size: 30rpx; font-weight: bold; text-align: center">
				订单-{{ orderId }}
			</view>
		</view>
		<su-fixed bottom :opacity="false" bg="" placeholder :noFixed="false" :index="10">
			<view class="footer-box ss-flex-col ss-row-between ss-p-20">
				<view v-if="state.currentTab === 0" class="ss-m-b-20" style="display: flex; justify-content: center">
					<button style="width: 33.3%; color: #FFFFFF; background: #459cff" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onScanProductId">扫码</button>
					<button style="width: 33.3%; color: #FFFFFF; background: #dc7d10" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSearchProductId">查询</button>
					<button style="width: 33.3%; color: #FFFFFF; background: #1fe85e" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSave">打包</button>
				</view>
				<view v-if="state.currentTab === 1" class="ss-m-b-20" style="display: flex; justify-content: center">
					<button style="width: 80%; color: #FFFFFF; background: #459cff" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSubmitNewOrderInExpress">提交</button>
				</view>
				<view v-if="state.currentTab === 2" class="ss-m-b-20" style="display: flex; justify-content: center">
					<button style="width: 80%; color: #FFFFFF; background: #459cff" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onPackExpressPrint">打印</button>
				</view>
			</view>
		</su-fixed>
		<su-dialog ref="suDialogRef"
		           :show="state.expressInfo.show"
		           title="包裹详情"
		           @confirm="state.expressInfo.show = false"
		           @cancel="state.expressInfo.show = false">
			<view class="ss-flex-col ss-p-20">
				<view class="modal-content content_box">
					<view style="position: relative; margin-top: 3%">
						<uni-table ref="table" border emptyText="暂无更多数据" stripe>
							<uni-tr>
								<uni-th align="center" width="220rpx">属性</uni-th>
								<uni-th align="center" width="80rpx">数值</uni-th>
							</uni-tr>
							<uni-tr v-for="(item, index) in state.expressInfo.kvData" :key="index">
								<uni-td>
									<text>{{ item.key }}</text>
								</uni-td>
								<uni-td>
									<text>{{ item.value }}</text>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</view>
			</view>
		</su-dialog>
		<view class="">
			<canvas canvas-id="mBarcode" :style="`width: ${state.print.canvasWidth}px; height: ${state.print.canvasHeight}px; z-index: -99`" />
		</view>
	</s-layout>
</template>

<script setup>
import { computed, watch, ref, reactive, unref } from 'vue';
import sheep from '@/sheep';
import { onLoad, onPageScroll } from '@dcloudio/uni-app';
import _, {clone} from 'lodash';
import { name, phone, detailAddress, region } from '@/sheep/validate/form';
// 引入baseUrl
import { baseUrl } from '@/sheep/config';

import {
	didReadPrintCountInfo,
	drawBarcode,
	drawText,
	endDrawLabel,
	startDrawLabel,
	startJob,
	print, drawQRCode
} from "@/static/JCAPI/JCAPI";

const addressFormRef = ref(null);

const tabMaps = [
	{
		name: '商品出库',
		value: '0',
	},
	{
		name: '虚拟商品',
		value: '1',
	},
	{
		name: '包裹打码',
		value: '2',
	}
];

const state = reactive({
	showRegion: false,
	currentTab: 0,
	printParamsBody: {},
	expressInfo: {
		show: false,
		kvData: [],
		detail: {

		}
	},
	model: {
		expressNo: '',
		wareName: '',
		productId: '',
		targetExpressNo: '',
		storageImgUrl: '',
		storageImgUrlList: [],
		size: '',
		pickerVal: 0,
		freightHeight: 0.0,
		wareTypeList: [
			{
				text: '普通',
				value: 0,
			},
			{
				text: '合箱',
				value: 1,
			}
		],
	},
	currentRes: {},
	print: {
		canvasWidth: 200,
		canvasHeight: 200,
	}
});

//选择售后类型
function onRefundChange(e) {
	state.model.wmsType = e.detail.value;
}

// 切换选项卡
function onTabsChange(e) {
	state.currentTab = e.index
	resetModel();
}

function resetModel() {
	state.model = {
		expressNo: '',
		productId: '',
		targetExpressNo: '',
		storageImgUrl: '',
		storageImgUrlList: [],
		size: '',
		pickerVal: 0,
		freightHeight: 0.0,
		wareTypeList: [
			{
				text: '普通',
				value: 0,
			},
			{
				text: '合箱',
				value: 1,
			}
		],
	}
	state.expressInfo = {
		show: false,
		kvData: [],
		detail: {

		}
	}
}

function onSelect(e) {
	console.log(e, 'select')
	console.log(state.model.storageImgUrlList, 'storageImgUrlList')
	const tempFilePaths = e.tempFilePaths
	state.model.storageImgUrlList.push(tempFilePaths[0])
}

function onDelete(e) {
	console.log(e, 'delete')
	console.log(state.model.storageImgUrlList, 'storageImgUrlList-delete-before')
	state.model.storageImgUrlList.splice(e.tempFilePath, 1)
	console.log(state.model.storageImgUrlList, 'storageImgUrlList-delete-after')
}

function onScanProductId() {
	if (sheep.$helper.isRealEmpty(state.model.wmsType)) {
		sheep.$helper.toast('请选择操作类型');
		return;
	}
	uni.scanCode({
		scanType: ['barCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			let wareId = res.result
			state.model.productId = wareId;
			sheep.$api.order.searchWareInExpress({
				wareId: wareId,
				wmsType: state.model.wmsType,
				expressNo: state.model.expressNo
			}).then(res => {
				console.log(res)
				// 弹出确认框
				uni.showModal({
					title: '是此包裹的商品',
					content: `查询到该商品是此包裹${state.model.expressNo}的的商品，请进一步确认后进行装箱出库操作`,
					showCancel: true,
					confirmText: '出库',
					success: function (res) {
						if (res.confirm) {
							// 确认出库
							sheep.$api.order.outWareInExpress({
								wareId: state.model.productId
							}).then(res => {
								console.log(res)
								if (res.length === 0) {
									uni.showModal({
										title: '出库成功',
										content: `包裹所有订单已完全出库，请核实`,
										showCancel: true,
										confirmText: '确认',
										success: function (res) {}
									});
								} else {
									uni.showModal({
										title: '出库成功',
										content: `包裹还剩${res.length}笔订单未出库，请核实`,
										showCancel: true,
										confirmText: '立即查看',
										success: function (res) {
											// 存在订单,跳转到包裹剩余商品详情
											sheep.$router.go('/pages/app/stockWare', {
												expressId: state.model.expressNo,
											})
										}
									});
								}
							})
						}
					}
				});
			})
		}
	});
}


function onSearchProductId() {
  if (sheep.$helper.isRealEmpty(state.model.wmsType)) {
    sheep.$helper.toast('请选择操作类型');
    return;
  }
  if (sheep.$helper.isRealEmpty(state.model.productId)) {
    sheep.$helper.toast('请输入商品ID')
  }

  sheep.$api.order.searchWareInExpress({
    wareId: state.model.productId,
    wmsType: state.model.wmsType,
    expressNo: state.model.expressNo
  }).then(res => {
    console.log(res)
    // 弹出确认框
    uni.showModal({
      title: '是此包裹的商品',
      content: `查询到该商品是此包裹${state.model.expressNo}的的商品，请进一步确认后进行装箱出库操作`,
      showCancel: true,
      confirmText: '出库',
      success: function (res) {
        if (res.confirm) {
          // 确认出库
          sheep.$api.order.outWareInExpress({
            wareId: state.model.productId
          }).then(res => {
            console.log(res)
            if (res.length === 0) {
              uni.showModal({
                title: '出库成功',
                content: `包裹所有订单已完全出库，请核实`,
                showCancel: true,
                confirmText: '确认',
                success: function (res) {}
              });
            } else {
              uni.showModal({
                title: '出库成功',
                content: `包裹还剩${res.length}笔订单未出库，请核实`,
                showCancel: true,
                confirmText: '立即查看',
                success: function (res) {
                  // 存在订单,跳转到包裹剩余商品详情
                  sheep.$router.go('/pages/app/stockWare', {
                    expressId: state.model.expressNo,
                  })
                }
              });
            }
          })
        }
      }
    });
  })
}

function onSearch() {
	if (sheep.$helper.isRealEmpty(state.model.expressNo)) {
		sheep.$helper.toast('请填写包裹编号');
		return;
	}
	sheep.$api.order.expressSearch({
		expressNo: state.model.expressNo
	}).then(res => {
		if (!sheep.$helper.isRealEmpty(res)) {
			state.expressInfo.detail = res;
			state.expressInfo.show = true;
		}
	})
}

async function onPackExpressPrint() {
	if (sheep.$helper.isRealEmpty(state.model.expressNo)) {
		sheep.$helper.toast('请填写包裹编号');
		return
	}
	sheep.$api.order.expressDetail({orderId: state.model.expressNo}).then(res => {
		state.expressInfo.detail = res
		console.log(state.expressInfo.detail)
		if (sheep.$helper.isRealEmpty(state.expressInfo.detail.orderId)) {
			sheep.$helper.toast('未查询到包裹信息')
			return
		}
		// 渠道
		let channelName = "";
		if (state.expressInfo.detail.sendType == 0) {
			channelName = `直邮-${state.expressInfo.detail.channelName}`;
		} else if (state.expressInfo.detail.sendType == 1) {
			channelName = "拼邮";
		}
		uniPrint(
				state.expressInfo.detail.orderId, // 包裹编号
				state.expressInfo.detail.memberId, // 会员ID
				channelName, // 渠道名称
				state.expressInfo.detail.createTime, // 申请打包时间
				state.expressInfo.detail.note, // 包裹备注
				state.expressInfo.detail.freightHeight, // 重量
				state.expressInfo.detail.size, // 尺寸
		)
	});
}

async function onPackExpressInfo() {
	uni.scanCode({
		scanType: ['barCode', 'qrCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			let expressNo = res.result
			state.model.expressNo = expressNo;
			sheep.$api.order.expressDetail({orderId: expressNo}).then(res => {
				state.expressInfo.detail = res
				console.log(state.expressInfo.detail)
				if (sheep.$helper.isRealEmpty(state.expressInfo.detail.orderId)) {
					sheep.$helper.toast('未查询到包裹信息')
					return
				}
				sheep.$router.go('/pages/order/express/detail', {
					id: state.expressInfo.detail.orderId,
					wms: true
				});
			});
		}
	});
}

function onScanPackExpressNoOfPinYou() {
	if (sheep.$helper.isRealEmpty(state.model.expressNo)) {
		sheep.$helper.toast('请填写包裹编号');
		return
	}

	if (sheep.$helper.isRealEmpty(state.model.targetExpressNo)) {
		sheep.$helper.toast('请填写合箱编号');
		return
	}

	sheep.$api.order.searchExpressInBigExpress({
		expressNo: state.model.expressNo,
		targetExpressNo: state.model.targetExpressNo
	}).then(res => {
		console.log(res)
		// 弹出确认框
		uni.showModal({
			title: '是此合箱的包裹',
			content: `查询到该包裹是此合箱${state.model.targetExpressNo}的的包裹，请进一步确认后进行装箱出库操作`,
			showCancel: true,
			confirmText: '出库',
			success: function (res) {
				if (res.confirm) {
					// 确认出库
					sheep.$api.order.outExpressInBigExpress({
						expressNo: state.model.expressNo
					}).then(res => {
						console.log(res)
						if (res) {
							sheep.$helper.toast('出库成功')
						} else {
							sheep.$helper.toast('出库失败')
						}
					})
				}
			}
		});
	})
}

function onSearchExpress() {
	if (sheep.$helper.isRealEmpty(state.model.targetExpressNo)) {
		sheep.$helper.toast('请填写合箱编号');
		return;
	}
	sheep.$api.order.expressSearch({
		expressNo: state.model.targetExpressNo
	}).then(res => {
		if (!sheep.$helper.isRealEmpty(res)) {
			state.expressInfo.detail = res;
			state.expressInfo.show = true;
		}
	})
}

function onScanPackNumber() {
	uni.scanCode({
		scanType: ['barCode','qrCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			state.model.expressNo = res.result
		}
	});
}

function onScanBigPackNumber() {
	uni.scanCode({
		scanType: ['barCode','qrCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			state.model.targetExpressNo = res.result
		}
	});
}

async function uploadFiles(urls) {
	if (urls.length === 0) {
		return; // 所有文件上传完成，结束递归
	}

	const filePath = urls[0];

	try {
		const res = await uni.uploadFile({
			url: baseUrl + '/no-auth/oss/upload',
			filePath: filePath,
			name: 'file'
		});

		if (res.statusCode === 200) {
			let data = JSON.parse(res.data);
			if (!sheep.$helper.isRealEmpty(data.url)) {
				state.model.storageImgUrl += data.url + ',';
			} else {
				sheep.$helper.toast(`图片${i + 1}上传失败，请稍后重新拍摄`);
			}
		}

	} catch (error) {
		sheep.$helper.toast(`图片${i + 1}上传失败，请稍后重新拍摄`);
	}

	// 继续上传下一个文件
	await uploadFiles(urls.slice(1));
}

function uniPrint(packId, memberId, channelName, createTime, note, freightHeight, size) {
	console.log('uniPrint', packId, memberId, channelName, createTime, note, freightHeight, size)
	//标签尺寸
	const labelWidth = 80
	const labelHeight = 40
	//B3S/B1/B21/B203/K3/K3W的mu tiple传8，B32/Z401/M2的mutiple传11.81
	const multiple = 15
	state.print.canvasWidth = labelWidth * multiple
	state.print.canvasHeight = labelHeight * multiple
	// 绘制条码
	let ctx = wx.createCanvasContext('mBarcode', this);
	ctx.setFillStyle('white');
	ctx.fillRect(0, 0, 200, 80);
	ctx.draw();
	ctx.setFillStyle('black');
	ctx.setFontSize(3);
	ctx.fillText('准备打印', 3, 20);
	ctx.draw();
	startDrawLabel('mBarcode', this, labelWidth, labelHeight)
	// default print params
	console.log(packId, '二维码内容')
	drawQRCode('' + packId, 27, 2, 15, 15)
	// drawText(`会员ID：${memberId}`, 8, 16, 3, 0)
	drawText(`邮寄渠道：${channelName}`, 10, 22, 3, 0)
	drawText(`包裹编号：${packId}`, 10, 25, 3, 0)
	drawText(`会员ID：${memberId}`, 10, 28, 3, 0)
	drawText(`重量：${freightHeight}kg`, 10, 31, 3, 0)
	drawText(`尺寸：${size}`, 10, 34, 3, 0)
	// drawText(`包裹备注：${note}`, 8, 24, 3, 0)
	// drawText(`申请时间：${createTime}`, 8, 28, 3, 0)
	/*if (!sheep.$helper.isRealEmpty(state.printParamsBody.barcode)) {
		drawBarcode(packId,
				state.printParamsBody.barcode.x,
				state.printParamsBody.barcode.y,
				state.printParamsBody.barcode.width,
				state.printParamsBody.barcode.height,
				state.printParamsBody.barcode.rotation,
				state.printParamsBody.barcode.fontSize,
				state.printParamsBody.barcode.fontHeight,
				state.printParamsBody.barcode.postion)
		/!*drawText(`会员ID：${memberId}`,
				state.printParamsBody.textRow.x,
				state.printParamsBody.textRow.y,
				state.printParamsBody.textRow.fontHeight,
				state.printParamsBody.textRow.rotation)*!/
		drawText(`邮寄渠道：${channelName}`,
				state.printParamsBody.textRow.x,
				state.printParamsBody.textRow.y + 4,
				state.printParamsBody.textRow.fontHeight,
				state.printParamsBody.textRow.rotation)
		/!*drawText(`包裹备注：${note}`,
				state.printParamsBody.textRow.x,
				state.printParamsBody.textRow.y + 4 * 2,
				state.printParamsBody.textRow.fontHeight,
				state.printParamsBody.textRow.rotation)*!/
		/!*drawText(`申请时间：${createTime}`,
				state.printParamsBody.textRow.x,
				state.printParamsBody.textRow.y + 4 * 3,
				state.printParamsBody.textRow.fontHeight,
				state.printParamsBody.textRow.rotation)*!/
	} else {
		// default print params
		drawBarcode(packId, 8, 3, 45, 15, 0, 4, 4, 1)
		// drawText(`会员ID：${memberId}`, 8, 16, 3, 0)
		drawText(`邮寄渠道：${channelName}`, 8, 20, 3, 0)
		// drawText(`包裹备注：${note}`, 8, 24, 3, 0)
		// drawText(`申请时间：${createTime}`, 8, 28, 3, 0)
	}*/

	endDrawLabel(() => {
		startJob(1, 3, 1,() => {
			print(1, (res) => {
				console.log(res)
			})
		})
	})

	didReadPrintCountInfo((res) => {
		console.log(res, '打印进度')
		if (res.count === 1) {
			uni.reLaunch({
				url: '/pages/app/pack',
			})
		}
	})
}

async function onSubmitNewOrderInExpress() {
	if (sheep.$helper.isRealEmpty(state.model.wmsType)) {
		sheep.$helper.toast('请选择操作类型');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.wareName)) {
		sheep.$helper.toast('请输入商品名称');
		return;
	}

	uni.showLoading({
		title: '上传中...',
		mask: true
	});

	try {
		await uploadFiles(state.model.storageImgUrlList);

		uni.hideLoading();

		if (sheep.$helper.isRealEmpty(state.model.expressNo)) {
			sheep.$helper.toast('请填写包裹编号');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.storageImgUrl)) {
			sheep.$helper.toast('请上传图片');
			return;
		}

		state.model.storageImgUrl = state.model.storageImgUrl.substring(0, state.model.storageImgUrl.length - 1);

		await sheep.$api.order.addNewOrderToExpress({
			expressNo: state.model.expressNo,
			warePic: state.model.storageImgUrl,
			wmsType: state.model.wmsType,
			wareName: state.model.wareName,
		}).then(res => {
			let content = "";
			if (!sheep.$helper.isRealEmpty(res)) {
				content = `新建成功`;
			} else {
				content = `新建失败，请重试`;
			}
			// 确认框
			uni.showModal({
				title: '提示',
				content: content,
				showCancel: false,
				confirmText: '确认',
				success: function (res) {
					if (res.confirm) {
						uni.reLaunch({
							url: '/pages/app/pack',
						})
					}
				}
			});
		})
	} catch (error) {
		uni.hideLoading();
		console.error(error);
	}
}

async function onSave() {
	if (sheep.$helper.isRealEmpty(state.model.wmsType)) {
		sheep.$helper.toast('请选择操作类型');
		return;
	}
	uni.showLoading({
		title: '上传中...',
		mask: true
	});

	try {
		await uploadFiles(state.model.storageImgUrlList);

		uni.hideLoading();

		if (sheep.$helper.isRealEmpty(state.model.expressNo)) {
			sheep.$helper.toast('请填写包裹编号');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.storageImgUrl)) {
			sheep.$helper.toast('请上传图片');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.size)) {
			sheep.$helper.toast('请填写包裹尺寸');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.freightHeight)) {
			sheep.$helper.toast('请填写包裹重量');
			return;
		}
		if (state.model.freightHeight <= 0) {
			sheep.$helper.toast('包裹重量必须大于0kg');
			return;
		}

		state.model.storageImgUrl = state.model.storageImgUrl.substring(0, state.model.storageImgUrl.length - 1);

		await sheep.$api.order.expressUpload({
			expressNo: state.model.expressNo,
			freightHeight: state.model.freightHeight,
			size: state.model.size,
			packPics: state.model.storageImgUrl,
			wmsType: state.model.wmsType
		}).then(res => {
			let content = "";
			state.currentRes = res;
			if (!sheep.$helper.isRealEmpty(res.id)) {
				content = `打包成功(●'◡'●)`;
			} else {
				content = `打包失败ಠ_ಠ | 请重新尝试，多次失败请联系管理员~`;
			}
			// 确认框
			uni.showModal({
				title: '提示',
				content: content,
				showCancel: true,
				cancelText: '继续打包',
				confirmText: '打印条码',
				success: function (res) {
					if (res.confirm) {
						// 渠道
						let channelName = "";
						if (state.currentRes.sendType == 0) {
							channelName = `直邮-${state.currentRes.channelName}`;
						} else if (state.currentRes.sendType == 1) {
							channelName = "拼邮";
						}
						uniPrint(
								state.currentRes.id, // 包裹编号
								state.currentRes.memberId, // 会员ID
								channelName, // 渠道名称
								state.currentRes.createTime, // 申请打包时间
								state.currentRes.note, // 包裹备注
								state.currentRes.freightHeight, // 重量
								state.currentRes.size, // 尺寸
						)
					} else {
						uni.reLaunch({
							url: '/pages/app/pack',
						})
					}
				}
			});
		})
	} catch (error) {
		uni.hideLoading();
		console.error(error);
	}
}

/**
 * 包裹出库 完成打包
 * @returns {Promise<void>}
 */
async function onSaveExpress() {
	uni.showLoading({
		title: '上传中...',
		mask: true
	});

	try {
		await uploadFiles(state.model.storageImgUrlList);

		uni.hideLoading();

		if (sheep.$helper.isRealEmpty(state.model.targetExpressNo)) {
			sheep.$helper.toast('请填写合箱编号');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.storageImgUrl)) {
			sheep.$helper.toast('请上传图片');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.size)) {
			sheep.$helper.toast('请填写包裹尺寸');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.freightHeight)) {
			sheep.$helper.toast('请填写包裹重量');
			return;
		}
		if (state.model.freightHeight <= 0) {
			sheep.$helper.toast('包裹重量必须大于0kg');
			return;
		}

		state.model.storageImgUrl = state.model.storageImgUrl.substring(0, state.model.storageImgUrl.length - 1);

		await sheep.$api.order.expressUpload({
			expressNo: state.model.expressNo,
			freightHeight: state.model.freightHeight,
			size: state.model.size,
			packPics: state.model.storageImgUrl
		}).then(res => {
			let content = "";
			state.currentRes = res;
			if (!sheep.$helper.isRealEmpty(res.id)) {
				content = `打包成功(●'◡'●)`;
			} else {
				content = `打包失败ಠ_ಠ | 请重新尝试，多次失败请联系管理员~`;
			}
			// 确认框
			uni.showModal({
				title: '提示',
				content: content,
				showCancel: true,
				cancelText: '继续打包',
				confirmText: '打印条码',
				success: function (res) {
					if (res.confirm) {
						// 渠道
						let channelName = "";
						if (state.currentRes.sendType == 0) {
							channelName = `直邮-${state.currentRes.channelName}`;
						} else if (state.currentRes.sendType == 1) {
							channelName = "拼邮";
						}
						uniPrint(
								state.currentRes.id, // 包裹编号
								state.currentRes.memberId, // 会员ID
								channelName, // 渠道名称
								state.currentRes.createTime, // 申请打包时间
								state.currentRes.note, // 包裹备注
								state.currentRes.freightHeight, // 重量
								state.currentRes.size, // 尺寸
						)
					} else {
						uni.reLaunch({
							url: '/pages/app/pack',
						})
					}
				}
			});
		})
	} catch (error) {
		uni.hideLoading();
		console.error(error);
	}
}

onLoad(async (options) => {
	let printParams = await sheep.$api.order.channelList({ type: 'print_params' });
	let dict = printParams[0];
	let printParamsBody = dict.dictValue;
	if (!sheep.$helper.isRealEmpty(printParamsBody)) {
		state.printParamsBody = JSON.parse(printParamsBody);
	}
});
</script>

<style lang="scss" scoped>
:deep() {
	.uni-forms-item__label .label-text {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
	}

	.uni-easyinput__content-input {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		padding-left: 0 !important;
	}

	.uni-easyinput__content-textarea {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		margin-top: 8rpx !important;
	}

	.uni-icons {
		font-size: 40rpx !important;
	}

	.is-textarea-icon {
		margin-top: 22rpx;
	}

	.is-disabled {
		color: #333333;
	}
}

.default-box {
	width: 100%;
	box-sizing: border-box;
	height: 100rpx;

	.default-box-title {
		font-size: 28rpx;
		color: #333333;
		line-height: normal;
	}
}

.footer-box {
	.save-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		color: $white;
	}

	.cancel-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: var(--ui-BG);
	}
}
</style>
